//
//  AppDelegate.m
//  ChunLaiZhuangClient
//
//  Created by zouzhisheng on 16/2/8.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "AppDelegate.h"
#import "MineViewController.h"
#import "ShopBagViewController.h"
#import "RanViewController.h"
#import "ClassViewController.h"
#import "HomeViewController.h"
#import "AppContext.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "QLKGuideView.h"
#import "SDWebImageManager.h"
#import "UMMobClick/MobClick.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    [[AppContext instance] setup];
    
    UMConfigInstance.appKey = @"56ce9c67e0f55afb0c00237a";
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    
    
    [WXApi registerApp:@"wxd5a2648dcc313d95" withDescription:@"ChunLaizhuang"];
   
    [self performSelectorInBackground:@selector(loadSpashView) withObject:0];
    
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    }

    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:nil];
    [self.window makeKeyAndVisible];
    
    
    return YES;
}
#pragma mark-获取当前的版本
-(void)getCurrentVersion{
    [ApiClient getCurrentVersionDidFinishLoaded:^(KXJson *json, NSString *path) {
        KXJson *kxJson=[json getJsonForKey:@"data"];
        _currentVersion=[kxJson getStringForKey:@"ios"];
        _ios_url=[kxJson getStringForKey:@"ios_url"];
        _update_message=[json getStringForKey:@"message"];
        [self checkVerson];
        //引导页
        [self addGuidView];
        
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
}

-(void)checkVerson{
    NSString *localVersion=[NSString getCurrentVersion];
    if ([localVersion floatValue]<[_currentVersion floatValue]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:_update_message message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去看看", nil];
        [alertView show];
    }
}
#pragma UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_ios_url]];
    }
    
}
-(CustomTabBarViewController*)tabBarController{
    if (!_tabBarController) {
        HomeViewController *homevc=[[HomeViewController alloc] init];
        ClassViewController *classvc=[[ClassViewController alloc] init];
        RanViewController*ranvc=[[RanViewController alloc] init];
        ShopBagViewController *shopVC=[[ShopBagViewController alloc] init];
        MineViewController *mineVC=[[MineViewController alloc] init];
        QLKNavigationController *nav1=[[QLKNavigationController alloc] initWithRootViewController:homevc];
        QLKNavigationController *nav2=[[QLKNavigationController alloc] initWithRootViewController:classvc];
        QLKNavigationController *nav3=[[QLKNavigationController alloc] initWithRootViewController:ranvc];
        QLKNavigationController *nav4=[[QLKNavigationController alloc] initWithRootViewController:shopVC];
        QLKNavigationController *nav5=[[QLKNavigationController alloc] initWithRootViewController:mineVC];
        _tabBarController=[[CustomTabBarViewController alloc] init];
        _tabBarController.viewControllers=[NSArray arrayWithObjects:nav1,nav2,nav3,nav4,nav5, nil];
        _tabBarController.selectedIndex=0;
        
    }
    return _tabBarController;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    //跳转支付宝钱包进行支付，需要将支付宝钱包的支付结果回传给SDK
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService]
         processOrderWithPaymentResult:url
         standbyCallback:^(NSDictionary *resultDic) {
             //支付宝支付返回
             [[NSNotificationCenter defaultCenter] postNotificationName:@"AliPayNotification" object:resultDic];
         }];
        return YES;
    }

    return [WXApi handleOpenURL:url delegate:self];
}

-(void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[SendMessageToWXResp class]]) {
         [[NSNotificationCenter defaultCenter] postNotificationName:@"WXShareSuccess" object:resp];
    }
}
#pragma mark-加载启动页
-(void)loadSpashView{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if ([userDefaults objectForKey:@"splash"]) {
        [self performSelectorOnMainThread:@selector(splashView) withObject:nil waitUntilDone:YES];
    }
    [ApiClient getSplashDidFinishLoaded:^(KXJson *json, NSString *path) {
        if ([[json getStringForKey:@"status"] intValue]==1) {
            [self getCurrentVersion];
            KXJson *kxjson=[json getJsonForKey:@"data"];
            if (![[userDefaults objectForKey:@"splash"] isEqualToString:[kxjson getStringForKey:@"splash"]]) {
                [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:[kxjson getStringForKey:@"splash"]] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                    NSData *data = UIImageJPEGRepresentation(image,1.0);
                    NSString *aPath=[NSString stringWithFormat:@"%@/Documents/splash.png",NSHomeDirectory()];
                    [data writeToFile:aPath atomically:YES];
                    [userDefaults setObject:[kxjson getStringForKey:@"splash"] forKey:@"splash"];
                    [userDefaults synchronize];
                    
                }];
                
               

            }
           
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
}
-(UIImageView *)splashView{
    if (!_splashView) {
        _splashView=[[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        UIImage *image=[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/Documents/splash.png",NSHomeDirectory()]];
        if (image) {
            _splashView.image=image;
        }
        self.guideWindow=[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        UIButton *bt=[UIButton buttonWithType:UIButtonTypeCustom];
        bt.frame=CGRectMake(SCREEN_WIDTH-74, 35, 130/2,74/2);
        [bt setImage:[UIImage imageNamed:@"btn_pass"] forState:UIControlStateNormal];
        [bt addTarget:self action:@selector(passAction:) forControlEvents:UIControlEventTouchUpInside];
        [_splashView addSubview:bt];
        _splashView.userInteractionEnabled=YES;
         timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
        [timer fire];
        [self.window addSubview:_splashView];

    }
    return _splashView;
}
#pragma mark-定时器
-(void)timeAction{
    static int count=3;
    count--;
    if (count==0) {
        [self remviewSplashView];
        [timer invalidate];
        
    }
}
#pragma mark-跳过方法
-(void)passAction:(UIButton*)bt{
    [self remviewSplashView];
}
-(void)remviewSplashView{
    [_splashView removeFromSuperview];

}
#pragma mark-添加引导页
-(void)addGuidView{
    NSString *localVersion=[NSString getCurrentVersion];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (![userDefaults objectForKey:@"isFirst"] || [localVersion floatValue]>[_currentVersion floatValue]) {
        [userDefaults setObject:@"1" forKey:@"isFirst"];
        [userDefaults synchronize];
        self.guideWindow=[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        self.guideWindow.windowLevel = UIWindowLevelStatusBar;
        QLKGuideView *guideView=[[QLKGuideView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        UIViewController *guideViewController = [[UIViewController alloc] init];
        guideViewController.view =guideView;
        [self.guideWindow setRootViewController:guideViewController];
        [self.guideWindow makeKeyAndVisible];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    application.applicationIconBadgeNumber=0;
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
//    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"Device Token: %@", deviceToken] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去升级", nil];
//     [alert show];
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示" message:error.localizedFailureReason delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去升级", nil];
     [alert show];
    
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


@end
